package cn.study.forkjointest.blocktask;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;

/**
 * @Author     ： 跟大佳一起学架构
 * @Description： CompletableFuture  他的future是保存结果的地方，任务只执行一次
 */
public class CompletableFutureDemo  {
    public static void main(String[] args) throws InterruptedException {
        List<CompletableFuture<Integer>> futures = new ArrayList<>();
        CompletableFuture<Integer> future1 = CompletableFuture.supplyAsync(() ->{
            try {
                System.out.println("future1 begin");
                Thread.sleep(3000);
                System.out.println("future1 end");
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            return 1;} );
        CompletableFuture<Integer> future2 = CompletableFuture.supplyAsync(() ->{
            try {
                System.out.println("future2 begin");
                Thread.sleep(2000);
                System.out.println("future2 end");
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            return 2;} );
        CompletableFuture<Integer> future3 = CompletableFuture.supplyAsync(() ->{
            try {
                System.out.println("future3 begin");
                Thread.sleep(1000);
                System.out.println("future3 end");
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            return 3;} );
        futures.add(future1);
        futures.add(future2);
        futures.add(future3);
        CompletableFuture<Void> allOf = CompletableFuture.allOf(futures.toArray(new CompletableFuture[0]));
        CompletableFuture<Integer>[] futureArray = futures.toArray(new CompletableFuture[0]);
        allOf.thenApply(v -> {
            for (CompletableFuture<Integer> future : futureArray) {
                try {
                    Integer batchMap = future.get(30000, TimeUnit.MILLISECONDS);
                    System.out.println("futureArray 循环，result:"+batchMap);
                } catch (Exception e) {
                }
            }
            return null;
        }).join();
        Thread.sleep(30000);
    }




}
